package com.jyw.framework.security.wechat;

import com.jyw.common.core.domain.model.MpLoginUserBinding;
import com.jyw.framework.web.service.WechatDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.ObjectUtils;

/**
 * @author 沈峻
 * @ClassName WechatAuthenticationProvider
 * @Description TODO
 * @Date 2023/9/5 16:17
 **/
@Slf4j
public class WechatAuthenticationProvider implements AuthenticationProvider {

    private WechatDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WechatAuthenticationToken authenticationToken = (WechatAuthenticationToken) authentication;
        MpLoginUserBinding bind = (MpLoginUserBinding) authenticationToken.getPrincipal();
        UserDetails userDetails = userDetailsService.loadUserByBody(bind);
        WechatAuthenticationToken token = new WechatAuthenticationToken(userDetails, userDetails.getAuthorities());
        token.setDetails(authenticationToken.getDetails());
        return token;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        //判断 authentication 是不是 WechatAuthenticationToken 的子类或子接口
        return WechatAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public void setUserDetailsService(WechatDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
